package com.bihucms.ssm.util;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by benhailong on 2017/10/19.
 */
public class BihuUtil {

    /**
     * 时间格式化 data 转 String
     * @param date 时间
     * @param type 状态
     * @return
     */
    public static String dataToString(Date date,int type){
        SimpleDateFormat simpleFormat = null;
        simpleFormat = getSimpleDateFormat(type);
        return simpleFormat.format(date);
    }

    /**
     * 时间格式化 String 转 data
     * @param string
     * @param type
     */
    public static Date stringToData(String string,int type){
        SimpleDateFormat simpleFormat = null;
        simpleFormat = getSimpleDateFormat(type);
        Date date = null;
        try {
            date = simpleFormat.parse(string);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    /**
     * 生成随机数
     * @param type 你要几位的验证码 默认可以使用 2-8 位的验证码，type 非法，直接返回6位
     */
    public static int randomNumber(int type){
        if(type==8){return (int)((Math.random()*9+1)*10000000);}
        if(type==7){return (int)((Math.random()*9+1)*1000000);}
        if(type==6){return (int)((Math.random()*9+1)*100000);}
        if(type==5){return (int)((Math.random()*9+1)*10000);}
        if(type==4){return (int)((Math.random()*9+1)*1000);}
        if(type==3){return (int)((Math.random()*9+1)*100);}
        if(type==2){return (int)((Math.random()*9+1)*10);}
        return (int)((Math.random()*9+1)*100000);
    }

    /**
     * 计算两个时间之间的时间
     * @param start   开始时间
     * @param end  结束时间
     * @param type 计算 1：分钟  2：小时  3：天
     * @return
     */
    public static int timeDifference(Date start, Date end, int type){
        int figure=0;
        // 时间改成String
        long from1 = start.getTime();
        long to1 = end.getTime();
//        秒
        if(type==1){
            figure = (int) ((to1 - from1)/(1000));
        }
//        分钟
        if(type==2){
            figure = (int) ((to1 - from1)/(1000 * 60));
        }
//        小时
        if(type==3){
            figure = (int) ((to1 - from1)/(1000 * 60 * 60));
        }
//        天
        if(type==4){
            figure = (int) ((to1 - from1)/(1000 * 60 * 60 * 24));
        }
        return figure;
    }
    /**
     * 返回Map集合
     */
    public static Map<String, Object> returnMap(String msg, String desc){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg",msg);
        map.put("desc",desc);
        return map;
    }
    /**
     * UUID
     */
    public static String uuid(){
        String uuid = UUID.randomUUID().toString();
        return uuid.replaceAll("-","");
    }

    /**
     * 邀请码
     */
    public static String generateRandomStr(int len) {
        //字符源，可以根据需要删减
        String generateSource = "23456789abcdefghgklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";//去掉1和i ，0和o
        String rtnStr = "";
        for (int i = 0; i < len; i++) {
            //循环随机获得当次字符，并移走选出的字符
            String nowStr = String.valueOf(generateSource.charAt((int) Math.floor(Math.random() * generateSource.length())));
            rtnStr += nowStr;
            generateSource = generateSource.replaceAll(nowStr, "");
        }
        return rtnStr;
    }

    /**
     * 保存图片
     */
    @Autowired
    private static ServletContext servletContext;

    public static String saveFile(MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // getRealPath() 取得 WEB-INF 所在文件夹路径
                // 如果参数是 "/temp", 当 temp 存在时返回 temp 的本地路径, 不存在时返回 null/temp (无效路径)
                String name= UUID.randomUUID()+file.getOriginalFilename();
                String path = servletContext.getRealPath("") + "/uplodefiles/"+  name;
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(path));
                String imgurl = "http://jsp.xw025.com"+"/uplodefiles/"+  name;
                return imgurl;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "1";
    }

    /**
     * 订单编号
     */
    public static String getOrderCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int a = (int)(Math.random()*(9999-1000+1))+1000;
        System.out.println(a);
        Date date = new Date();
        String str = sdf.format(date);
        String[] split = str.split("-");
        String s = split[0] + split[1] + split[2];
        String[] split1 = s.split(" ");
        String s1 = split1[0] + split1[1];
        String[] split2 = s1.split(":");
        String s2 = split2[0] + split2[1] + split2[2]+a;
        System.out.println(s2);
        return s2;
    }


    /**
     * 时间调用
     * @param type
     * @return
     */
    private static SimpleDateFormat getSimpleDateFormat(int type) {
        SimpleDateFormat simpleFormat;
        if(type==1){
            simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");//如2016-08-10 20:40
        } else if(type==2){
            simpleFormat = new SimpleDateFormat("yyyy-MM-dd");//如2016-08-10
        } else if(type==3){
            simpleFormat = new SimpleDateFormat("yyyy/MM");//如2016-08-10
        } else if(type==4){
            simpleFormat = new SimpleDateFormat("yyyyMMdd");//如2016-08-10
        } else if(type==5){
            simpleFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//如2016-08-10
        } else if(type==6){
            simpleFormat = new SimpleDateFormat("yyyyMMddHHmmss");//如2016-08-10
        } else if(type==7){
            simpleFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");//如2016-08-10
        } else if(type==8){
            simpleFormat = new SimpleDateFormat("HH:mm:ss");//如2016-08-10
        } else if(type==9){
            simpleFormat = new SimpleDateFormat("HH:mm");//如2016-08-10
        } else if(type==10){
            simpleFormat = new SimpleDateFormat("HHmm");//如2016-08-10
        } else {
            simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//如2016-08-10
        }

        return simpleFormat;
    }

    /**
     * 去除指定字符
     * @param resource  字符串
     * @param ch  需要去除的字符  如：char c=' ';
     * @return
     */
    public static String remove(String resource,char ch) {
        StringBuffer buffer=new StringBuffer();
        int position=0;
        char currentChar;

        while(position<resource.length()) {
            currentChar=resource.charAt(position++);
            //如果当前字符不是要去除的字符，则将当前字符加入到StringBuffer中
            if(currentChar!=ch) buffer.append(currentChar);
        }
        return buffer.toString();
    }

    /**
     * 非空验证
     */
    public static Map<String,Object> isNull(Map<String, Object> map){
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if(entry.getValue() == null || "".equals(entry.getValue())){
                return returnMap("300","参数："+entry.getKey()+" 不能为空！");
            }
        }
        return returnMap("200","");
    }

    /**
     * 将Javabean转换为Map
     *
     * @param javaBean
     *            javaBean
     * @return Map对象
     */
    public static Map toMap(Object javaBean) {
        Map result = new HashMap();
        Method[] methods = javaBean.getClass().getDeclaredMethods();
        for (Method method : methods) {
            try {
                if (method.getName().startsWith("get")) {
                    String field = method.getName();
                    field = field.substring(field.indexOf("get") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);

                    Object value = method.invoke(javaBean, (Object[]) null);
                    result.put(field, null == value ? "" : value.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 将Json对象转换成Map
     *
     * @param jsonString
     *            json对象
     * @return Map对象
     * @throws JSONException
     */
    public static Map toMap(String jsonString) throws JSONException {
        JSONObject jsonObject = new JSONObject(jsonString);
        Map result = new HashMap();
        Iterator iterator = jsonObject.keys();
        String key = null;
        String value = null;
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            value = jsonObject.getString(key);
            result.put(key, value);
        }
        return result;
    }

    /**
     * 将JavaBean转换成JSONObject（通过Map中转）
     *
     * @param bean
     *            javaBean
     * @return json对象
     */
    public static JSONObject toJSON(Object bean) {
        return new JSONObject(toMap(bean));
    }

    /**
     * 将Map转换成Javabean
     *
     * @param javabean
     *            javaBean
     * @param data
     *            Map数据
     */
    public static Object toJavaBean(Object javabean, Map data) {
        Method[] methods = javabean.getClass().getDeclaredMethods();
        for (Method method : methods) {
            try {
                if (method.getName().startsWith("set")) {
                    String field = method.getName();
                    field = field.substring(field.indexOf("set") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);
                    method.invoke(javabean, new Object[] {
                            data.get(field)
                    });
                }
            } catch (Exception e) {
            }
        }
        return javabean;
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {



    }


}
